// pages/grabSuccess/grabSuccess.js
const app=getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hours: '0' + 0, // 时
    minute: '0' + 0, // 分
    second: '0' + 0, // 秒
    isShow: false,
    open: true,
    count: 0,
    time: '',
    projectMes: [],
    reportContent: '', //报告内容
    reportImgs: [], //报告施工图片
    commentContent: '', //评价内容
    // commentImgs: [],                    //评价图片
    star: 5, //评价星星数量
    companyPhone: '',
    companyName: '',
    phone: null,
    createTime: '',
    name: '',
    orderId: null,
    orderNo: '',
    serviceAddr: '',
    serviceCate: '',
    serviceDesc: '',
    serviceFee: null,
    status: null,
    totalFee: null,
    serviceFee: null,
    feeItemIds: [],
    orderOpen: false,
    top: "",
    statusName: "",
    statusNameLast: "",
    statusNameNext: "",
    picArr: [],
    location: "",
    lat:"",
    lng:"",
    distance:0,
    sceneImg: [],
    processData: [{
      name: '抢单成功',
      // start: '../../icons/lin1.png',
      end: '../../icons/lin1.png',
      icon: '../../icons/l7.png',
      time: ""
    },
    {
      name: '等待发单方确认',
      start: '../../icons/lin1.png',
      end: '../../icons/lin1.png',
      icon: '../../icons/l3.png',
      time: ""
    },
    {
      name: '前往施工地点',
      start: '../../icons/lin2.png',
      end: '../../icons/lin2.png',
      icon: '../../icons/l8.png',
      time: ""
    },
    {
      name: '正在赶往途中',
      start: '../../icons/lin2.png',
      end: '../../icons/lin2.png',
      icon: '../../icons/l8.png',
      time: ""
    },
    {
      name: '开始施工',
      start: '../../icons/lin2.png',
      end: '../../icons/lin2.png',
      icon: '../../icons/l8.png',
      time: ""
    },
    {
      name: '施工已完成',
      start: '../../icons/lin2.png',
      end: '../../icons/lin2.png',
      icon: '../../icons/l8.png',
      time: ""
    },
    {
      name: '订单已完成',
      start: '../../icons/lin2.png',
      icon: '../../icons/l8.png',
      end: '../../icons/lin2.png',
      time: ""
    }
    ],
  },






  /**
   *     计时器
   */
  interVal: function () {
    let that = this;
    console.log(that.data.orderId)
    wx.request({
      url: 'https://www.xiaozheng8.com/clock/get',
      data: {
        orderId: that.data.orderId,
        userType: 1,
      },
      method: 'post',
      success: function (res) {
        console.log(res)
        console.log("--sjian--")
        that.setData({
          hours: parseInt(res.data.data / 3600)
        })
        let count = res.data.data % 3600;
        // console.log(count)
        that.data.timeInterval = setInterval(function () {
          count++
          // console.log(count)
          if (count % 60 < 10) {
            that.setData({
              second: '0' + count % 60
            })
          } else {
            that.setData({
              second: count % 60
            })
          }
          if (parseInt(count / 60) < 10) {
            that.setData({
              minute: '0' + parseInt(count / 60)
            })
          } else {
            that.setData({
              minute: parseInt(count / 60),
            })
          }
        }, 1000)
      }
    })
  },
  /**
   * 获取施工报告
   */
  getReport: function () {
    let that = this;
    wx.request({
      url: 'https://www.xiaozheng8.com/service/report/findById',
      method: 'post',
      data: {
        orderId: that.data.orderId
      },
      success: function (res) {
        console.log(res);
        if (res.data.data == null) { } else {
          that.setData({
            reportContent: res.data.data.content,
            reportImgs: res.data.data.imgs,
          })
        }
        console.log("--施工报告--")
        console.log(res)
      }
    })
  },

  /**
   *获取评价
   */
  getComment: function () {
    let that = this;
    wx.request({
      url: 'https://www.xiaozheng8.com/service/comment/findById',
      method: 'post',
      data: {
        orderId: that.data.orderId
      },
      success: function (res) {
        console.log(res);
        console.log(res.statusCode)
        console.log("---res--")
        console.log(res.data.data.content);
        if (res.statusCode == 500) {

        } else if (res.data.data.content == '') {
          res.data.data.content = "发单方未填写评价"

          that.setData({
            commentContent: res.data.data.content,
            star: res.data.data.grade
          })
          console.log(that.data.commentContent)
        }
      }
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    wx.showLoading({
      title: '加载中',
    })
    var orderId = options.orderId;
    this.setData({
      orderId: orderId
    })

    this.request();

    // if (this.data.getTime == "") {
    //   wx.showLoading({
    //     title: "加载中",
    //     mask: true,
    //     success: function(res) {
    //       that.setData({
    //         page: false
    //       })
    //     }
    //   });
    // }
    console.log(this.data.statusNameLast)
    this.beforeWorkPic();
  },
  // 获取数据
  request: function () {
    var that = this;
    /**
     * 请求未完成订单列表
     */
    wx.request({
      url: 'https://www.xiaozheng8.com/serviceOrder/receiveFindById',
      method: 'post',
      data: {
        orderId: that.data.orderId,
        userId: wx.getStorageSync("userId")
      },
      success: function (res) {
        console.log(res)
        console.log("==aaa==")
        if (res.data.code === 200) {

          that.setData({
            statusName: res.data.data.statusName,
            // top:res.data.data.msg,
            // statusNameNext: res.data.data.statusNameNext,
            // orderInfo: [res.data.data],
            companyName: res.data.data.companyName,
            companyPhone: res.data.data.companyPhone,
            phone: res.data.data.phone,
            createTime: res.data.data.createTime,
            name: res.data.data.name,
            orderId: res.data.data.orderId,
            orderNo: res.data.data.orderNo,
            serviceAddr: res.data.data.serviceAddr,
            // serviceCate: res.data.data.serviceCate,
            serviceDesc: res.data.data.serviceDesc,
            serviceFee: res.data.data.serviceFee,
            status: res.data.data.status,
            totalFee: res.data.data.totalFee,
            serviceFee: res.data.data.serviceFee,
            feeItemIds: res.data.data.feeItemIds,
            projectMes: res.data.data.project,
            sendClick: res.data.data.sendClick,
            lat:res.data.data.lat,
            lng:res.data.data.lng,
            distance: res.data.data.distance
          })
          let distance = Math.round(that.data.distance / 1000)
          console.log(that.data.distance)
          that.setData({
            distance: distance
          })
          console.log(that.data.sendClick)
          // if(that.data.sendClick==0){
          that.setData({
            statusName: that.data.statusName
          })

          /**
           * 费用明细
           */
          let fee = res.data.data.feeItemIds;
          // console.log(fee
          that.data.feeItemIds = fee.split(" ");
          that.setData({
            feeItemIds: that.data.feeItemIds,
          })
          that.flow();
          // 根据日志来更改订单流程

          // that.flow();
          that.log();
          if(that.data.status>=8){
            that.beforeWork();
          }
          if (that.data.status > 8) {
            that.getReport();
          }
          if (that.data.status > 10) {
            that.getComment();
          }



        }
      }, fail(res) {
        wx.showLoading({
          title: '加载失败',
        })
      }
    })

  },
  // 流程图
  flow: function () {
    var that = this;
    // 根据日志获取流程
    wx.request({
      url: 'https://www.xiaozheng8.com/serviceOrder/log/v2',
      method: "post",
      data: {
        orderId: that.data.orderId,
        userType: 1
      },
      success: function (res) {
        for (var i = 0; i < res.data.data.length; i++) {
          if (res.data.data.length != that.data.processData.length) {
            var addList = '{"name": "正在施工","start": "../../icons/lin2.png","end":"../../icons/lin2.png","icon": "../../icons/l8.png","time": ""} ';
            console.log(JSON.parse(addList));
            that.data.processData.push(JSON.parse(addList));
            that.setData({
              processData: that.data.processData,
              top: res.data.msg
            })

            console.log(that.data.processData);

          }
        }
        for (var i = 0; i < res.data.data.length; i++) {
          if (i + 1 != res.data.data.length) {

            if (res.data.data[i].isOk == true && res.data.data[i + 1].isOk == false) {
              console.log(res.data.data.length);
              console.log(i);

              that.data.processData[i].start = '../../icons/lin1.png';
              that.data.processData[i].end = '../../icons/lin1.png';
              that.data.processData[i].icon = '../../icons/l7.png';
              that.data.processData[i + 1].start = '../../icons/lin1.png';
              that.data.processData[i + 1].end = '../../icons/lin1.png';
              that.data.processData[i + 1].icon = '../../icons/l3.png';
              that.setData({
                processData: that.data.processData
              });
              for (var j = 0; j < i; j++) {
                that.data.processData[j].start = '../../icons/lin1.png';
                that.data.processData[j].end = '../../icons/lin1.png';
                that.data.processData[j].icon = '../../icons/l7.png';
                that.setData({
                  processData: that.data.processData
                });
              }
            }
          } else if (i + 1 == res.data.data.length && res.data.data[i].isOk == true) {
            for (var j = 0; j < i; j++) {
              that.data.processData[j].start = '../../icons/lin1.png';
              that.data.processData[j].end = '../../icons/lin1.png';
              that.data.processData[j].icon = '../../icons/l7.png';
              that.setData({
                processData: that.data.processData
              });
            }
            that.data.processData[i].start = '../../icons/lin1.png';
            that.data.processData[i].end = '../../icons/lin1.png';
            that.data.processData[i].icon = '../../icons/l7.png';
            that.setData({
              processData: that.data.processData
            })

          }
        }
        that.data.processData[0].start = "",
          that.data.processData[that.data.processData.length - 1].end = '',
          that.setData({
            processData: that.data.processData
          });
        console.log(that.data.processData);
        that.log();
        wx.hideLoading();
      }
    });
  },
  // 获取日志并返回时间
  log: function () {
    var that = this;
    // 通过日志获取时间和文字介
    var that = this;
    console.log(that.data.processData);
    wx.request({
      url: 'https://www.xiaozheng8.com/serviceOrder/log/v2',
      method: "post",
      data: {
        orderId: that.data.orderId,
        userType: 1
      },
      success: function (res) {
        console.log(res);
        var time = [];
        console.log(res.data.data);
        time = res.data.data
        console.log(time);
        that.setData({
          getTime: time,
          top: res.data.msg
        });
        console.log(that.data.getTime);
        console.log(that.data.processData);
        for (var i = 0; i < that.data.getTime.length; i++) {
          that.data.processData[i].name = that.data.getTime[i].des;
          if (that.data.getTime[i].isOk == true) {
            that.data.processData[i].time = that.data.getTime[i].time;
            that.setData({
              processData: that.data.processData
            });
            if (i + 1 == that.data.getTime.length) {
              that.data.processData[i].time = that.data.getTime[i - 1].time;
              that.setData({
                processData: that.data.processData
              });
            }
          }
          that.setData({
            processData: that.data.processData
          });
          // console.log(that.data.processData);
        }
      

      }

    });

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.interVal();
    this.flow();
    this.log();
    this.request();
    var that = this;
    if (that.data.status > 6) {
      that.beforeWork();
    }


    if (this.data.status > 5) {
      clearInterval(that.data.timeInterval)
    }
  },
  // 发单方上传施工现场图片获取
  // 如果上传了施工前图片，显示施工现场图片
  beforeWorkPic() {
    var that = this;
    wx.request({
      url: 'https://www.xiaozheng8.com/order/img/findByOrderId',
      data: {
        orderId: that.data.orderId
      },
      method: 'post',
      success: (res) => {
        console.log(res);
        that.setData({
          sceneImg: res.data.data
        })
      },
      fail: (res) => {
        console.log(res);
      },
      complete: () => { }
    });

  },
  // 施工前报告
  beforeWork: function () {
    var that = this;
    console.log(that.data.statusName);
    wx.request({
      url: 'https://www.xiaozheng8.com/service/order/findImg',
      data: {
        orderId: that.data.orderId
      },
      method: 'post',
      success: function (res) {
        console.log(res);
        var pic = res.data.data.images.split("@");
        that.setData({
          location: res.data.data.address,
          picArr: pic
        })
        // that.next();
        console.log(that.data.picArr);
      },
      fail: function (res) { },
      complete: function (res) { },
    })
  },

  /**
   * 进入下一个状态
   */
  next: function (e) {
    let that = this;
    that.onReady();
    var statusName = "";
    console.log(that.data.statusName);
    if (that.data.statusName == "前往施工地点") {
      wx.showModal({
        title: '提示',
        content: '前往施工地点',
        success(sure) {
          if (sure.confirm) {
            wx.getLocation({
              success: function (response) {
                console.log(response);
                wx.request({
                  url: 'https://www.xiaozheng8.com/location/updateByReceiveUserId',
                  data: {
                    userId: wx.getStorageSync("userId"),
                    lat: response.latitude,
                    lng: response.longitude
                  },
                  method: 'post',
                  success: function (res) {
                    console.log(res);
                    wx.request({
                      url: 'https://www.xiaozheng8.com/serviceOrder/setStatus/v3',
                      method: 'post',
                      data: {
                        orderId: that.data.orderId,
                        status: that.data.status,
                        userId: wx.getStorageSync("userId")
                      }, success(response) {
                        console.log(response);
                        that.request();
                        that.flow();
                        that.log();

                      }
                    })
                  },
                  fail: function (res) { },
                  complete: function (res) { },
                })
              },
            })
          }
        }
      })

    } else
      if (that.data.statusName == "开始施工") {
        wx.showModal({
          title: '提示',
          content: '请上传现场图片',
          success: function (res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '../construction/construction?status=' + that.data.status + "&orderId=" + that.data.orderId,
              })
            }
          }
        })
      }
      // if (that.data.status == 6) {
      else if (that.data.statusName == "施工完成并填写施工报告") {
        wx.showModal({
          title: '提示',
          content: "是否确认施工已完成",
          cancelText: '取消',
          cancelColor: '#999',
          confirmText: '确认',
          confirmColor: '#0bbd79',
          success: function (res) {
            if (res.confirm) {
              wx.redirectTo({
                url: '../report/report?orderId=' + that.data.orderId + '&serviceDesc=' + that.data.serviceDesc
              })
            }
          }
        })

      } else {
        wx.showModal({
          title: '提示',
          content: "" + that.data.statusName + "",
          cancelText: '取消',
          cancelColor: '#999',
          confirmText: '确认',
          confirmColor: '#0bbd79',
          success: function (res) {
            if (res.confirm) {
              wx.request({
                url: 'https://www.xiaozheng8.com/serviceOrder/setStatus/v3',
                method: 'post',
                data: {
                  orderId: that.data.orderId,
                  status: that.data.status,
                  userId: wx.getStorageSync("userId")
                },
                success: function (res) {
                  console.log(res)
                  that.setData({
                    info: "正在路途中，请确认到达施工地点",
                    btnText: '到达施工地点',
                    status: res.data.data
                  })
                  that.request();
                  console.log(that.data.status);
                  that.flow();
                  that.log();
                },

              })

            } else {
              // console.log('用户点击取消')
            }

          }
        })
      }

  },


  isShow: function () {

    this.setData({
      isShow: !this.data.isShow
    })
  },
  // 订单进度收起
  orderInfo: function () {
    this.setData({
      orderOpen: !this.data.orderOpen,

    })
  },
// 地图
  map: function () {
    let that = this;
    wx.getSetting({
      success: (res) => {
        console.log(res);
        if (!res.authSetting['scope.userLocation'])
          app.openConfirm()
      }, fail(res) {
        console.log(res);
      }
    })
    wx.request({
      url: 'https://www.xiaozheng8.com/serviceOrder/receiveFindById',
      method: "post",
      data: {
        publishId: that.data.orderId,
        userId: wx.getStorageSync("userId"),
      },
      success: function (res) {

        // 设置自己位置设置为lat2,发单方位置为lat1
        wx.getLocation({
          success: function (res) {
            wx.navigateTo({
              url: '../map/map?lat1=' + that.data.lat + "&lng1=" + that.data.lng + "&lat2=" + res.latitude + "&lng2=" + "&lng2=" + res.longitude,
            })
          },
        })

        // wx.getLocation({ //获取当前经纬度
        //   altitude: true,
        //   type: 'wgs84', //返回可以用于wx.openLocation的经纬度
        //   success: function(res) {
        //     wx.openLocation({ //​使用微信内置地图查看位置。
        //       latitude: that.data.lat, //要去的纬度-地址
        //       longitude: that.data.lng, //要去的经度-地址
        //     })
        //     wx.hideLoading()
        //     console.log("成功")
        //   },fail(res){
        //     wx.hideLoading()
        //   }
        // })

      }

    })
  },

  onPullDownRefresh: function () {
    // console.log('下拉')
    // wx.startPullDownRefresh();
    this.request();
    setTimeout(() => {
      wx.stopPullDownRefresh()
    }, 1000)
  },

  /**
   * 减少事件
   */
  minus: function () {
    this.setData({
      count: this.data.count - 1,
    })
    this.setData({
      totalFee: this.data.totalFee - 1,
      serviceFee: this.data.serviceFee - 1,
    })
  },

  /**
   * 增加事件
   */
  plus: function () {
    this.setData({
      count: this.data.count + 1,
    })
    this.setData({
      totalFee: 1 + this.data.totalFee,
      serviceFee: 1 + this.data.serviceFee,
    })
  },

  /**
   * 收起事件
   */
  collapse: function () {
    this.setData({
      open: !this.data.open
    })
  },

  /**
   * 调用电话事件
   */
  phone: function () {
    wx.makePhoneCall({
      phoneNumber: this.data.phone
    })
  },

  /**
   * 图片预览
   */
  imgPreview: function (e) {
    let img = e.currentTarget.dataset.src;
    console.log(img)
    wx.previewImage({
      urls: [img],
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    clearInterval(this.data.timeInterval)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearInterval(this.data.timeInterval)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})